<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i>资质管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="query.picName" placeholder="文件名称" class="handle-input mr10"
                          @keyup.enter.native="handleSearch" style="width: 180px"></el-input>
                <el-select v-model="query.picType" placeholder="请选择文件类型" @keyup.enter.native="handleSearch"
                           style="margin-right: 10px">
                    <el-option label="图片" key="00"
                               value="00"></el-option>
                    <el-option label="PDF" key="01"
                               value="01"></el-option>
                </el-select>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="el-button" icon="el-icon-delete" @click="handleReset">重置</el-button>
                <div class="right-items" style="float: right;">
                    <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
                </div>
            </div>
            <el-table
                    :data="pictureData"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
            >
                <el-table-column prop="picId" label="文件编号" align="center" width="200"></el-table-column>
                <el-table-column prop="picName" label="文件名称" align="center"></el-table-column>
                <el-table-column prop="picType" label="文件类型" align="center">
                    <template slot-scope="scope">
                        <span v-if="scope.row.picType=='00'">图片</span>
                        <span v-if="scope.row.picType=='01'">PDF</span>
                    </template>
                </el-table-column>
                <!--  <el-table-column label="详情" align="center">
                      <template slot-scope="scope">
                        &lt;!&ndash;  <img  :src="'data:image/'+ scope.row.picImgTp +';base64,' + scope.row.picImgData" @click="clickImg($event)"
                               class="user-header-img user-header-com">&ndash;&gt;

                      </template>
                  </el-table-column>-->
                <el-table-column label="文件(查看)" align="center">
                    <template slot-scope="scope">
                        <el-image v-if="scope.row.picType=='00'"
                                  class="table-td-thumb"
                                  :src="'data:image/'+ scope.row.picImgTp +';base64,' + scope.row.picImgData"
                                  @click="onPreview('data:image/'+ scope.row.picImgTp +';base64,' +
                            scope.row.picImgData)"></el-image>
                        <el-image-viewer
                                v-if="showImg"
                                :on-close="closeViewer"
                                :url-list="srcList"/>
                        <el-link v-if="scope.row.picType=='01'" type="primary" @click="showPdf(scope.$index, scope.row)"
                        >{{scope.row.picAdr}}
                        </el-link>
                    </template>
                </el-table-column>
                <el-table-column prop="createdAccount" label="创建人" align="center"></el-table-column>
                <el-table-column prop="createdTime" label="创建时间" align="center"></el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.$index, scope.row)"
                        >编辑
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-delete"
                                class="red"
                                @click="handleDelete(scope.$index, scope.row)"
                        >删除
                        </el-button>
                        <el-button v-if="scope.row.picType=='01'"
                                   type="text"
                                   icon="el-icon-download"
                                   @click="handleLoad(scope.$index, scope.row)"
                        >下载
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="query.pageIndex"
                        :page-size="query.pageSize"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 新增弹出框 -->
        <el-dialog title="新增" :visible.sync="addVisible" width="50%" :before-close="closeAdd">
            <el-form ref="addForm" :rules="formRules" :model="addForm" label-width="100px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="文件类型:" prop="picType">
                            <el-select v-model="addForm.picType" @change="selectPicType">
                                <el-option key="00" label="图片" value="00"></el-option>
                                <el-option key="01" label="PDF" value="01"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="文件名称:" prop="picName">
                            <el-input v-model="addForm.picName"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="文件">
                             <span slot="label">
                                 <span style="color: red;margin-right: 4px">*</span>文件
                                 </span>
                            <div v-if="isImg" class="user-header">
                                <input type="file" name="image" accept="image/*"
                                       @change='onchangeImgFun'
                                       class="header-upload-btn user-header-com">
                                <img :src="require('../assets/img/upload.png')"
                                     class="user-header-img user-header-com">
                                <img v-if="imgurl!==undefined && imgurl!==''" alt="" :src='imgurl'
                                     class="user-header-img user-header-com">
                            </div>
                            <el-upload v-if="!isImg"
                                       class="upload-demo"
                                       drag
                                       :limit="1"
                                       :on-remove="handleRemove"
                                       :on-exceed="handleExceed"
                                       :before-upload="beforeUpload"
                                       action=""
                                       :http-request="handlePost"
                                       accept=".pdf"
                                       :file-list="fileList">
                                <i class="el-icon-upload"></i>
                                <div class="el-upload__text"><em>点击上传</em></div>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="说明:" prop="picRmk">
                            <el-input type="textarea" v-model="addForm.picRmk"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeAdd">取 消</el-button>
                <el-button type="primary" @click="saveAdd">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="50%" :before-close="closeEdit">
            <el-form ref="editForm" :rules="formRules" :model="editForm" label-width="100px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="文件类型:" prop="picType">
                            <el-select disabled v-model="editForm.picType" placeholder="请选择文件类型" @change="selectPicType">
                                <el-option key="00" label="图片" value="00"></el-option>
                                <el-option key="01" label="PDF" value="01"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="文件名称:" prop="picName">
                            <el-input v-model="editForm.picName"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="文件:" prop="picAdr">
                               <span slot="label">
                                 <span style="color: red;margin-right: 4px">*</span>文件
                                 </span>
                            <div class="user-header" v-if="isImg">
                                <input type="file" name="image" accept="image/*"
                                       @change='onchangeImgFun'
                                       class="header-upload-btn user-header-com">
                                <img :src="require('../assets/img/upload.png')"
                                     class="user-header-img user-header-com">
                                <img v-if="imgurl!==undefined && imgurl!==''" alt="" :src='imgurl'
                                     class="user-header-img user-header-com">
                            </div>
                            <span v-if="!isImg">{{this.editForm.picAdr}}</span>
                            <el-upload v-if="!isImg"
                                       class="upload-demo"
                                       drag
                                       :limit="1"
                                       :on-remove="handleRemove"
                                       :on-exceed="handleExceed"
                                       action=""
                                       :before-upload="beforeUpload"
                                       :http-request="handlePost"
                                       accept=".pdf"
                                       :file-list="fileList">
                                <i class="el-icon-upload"></i>
                                <div class="el-upload__text"><em>点击上传</em></div>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="说明:" prop="picRmk">
                            <el-input type="textarea" v-model="editForm.picRmk"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeEdit">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="预览" :visible.sync="pdfDlgVisible" width="60%">
            <div style="text-align: center">
                <span style="margin-right: 20px;font-size: 20px">{{currentPage}} / {{pageCount}}</span>
                <el-button style="margin-right: 12px;font-size: 20px" @click="change1">上一页</el-button>
                <el-button style="font-size: 20px" @click="change2">下一页</el-button>
            </div>
            <br>
            <pdf
                    :src="src"
                    :page="currentPage"
                    @num-pages="pageCount=$event"
                    @page-loaded="currentPage=$event"
                    @loaded="loadPdfHandler">
            </pdf>
            <span slot="footer" class="dialog-footer">
                <el-button style="font-size: 20px" @click="closeSee">关闭</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
    import {
        selectPictureByFkId,
        doAddPicture,
        doDeletePicture,
        selectOnePic,
        doUpdatePicture,
        showPdf
    } from '../api/picture';
    import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
    import pdf from 'vue-pdf'

    export default {
        name: 'contacts',
        data() {
            return {
                query: {
                    fkId: this.$route.query.fkId,
                    picName: '',
                    picType: '',
                    pageIndex: 1,
                    pageSize: 10
                },
                pictureData: [],
                pageTotal: 0,
                showImg: false,
                imgSrc: {},
                imgurl: '',
                editVisible: false,
                addVisible: false,
                addForm: {},
                editForm: {},
                srcList: [],
                isImg: true,
                file: File,
                fileSize: 0,
                fileList: [],
                currentPage: 0, // pdf文件页码
                pageCount: 0, // pdf文件总页数
                fileType: 'pdf', // 文件类型
                src: '',
                pdfDlgVisible: false,
                formRules: {
                    picType: [
                        {required: true, message: '请选择文件类型', trigger: 'blur'},
                    ],
                    picName: [
                        {required: true, message: '请输入文件名称', trigger: 'blur'},
                    ],
                },
            };
        },
        created() {
            this.getData();
        },
        components: {
            ElImageViewer,
            pdf
        },
        methods: {
            // 获取后台数据
            getData() {
                console.log("this.query", this.query);
                selectPictureByFkId(this.query).then(res => {
                    if (res.success == true) {
                        this.pictureData = res.data;
                        this.pageTotal = res.total;
                    } else {
                        this.$message.error("查询失败！");
                        this.pictureData = [];
                    }
                });
            },
            change1() {
                if (this.currentPage > 1) {
                    this.currentPage--
                }
            },
            change2() {
                if (this.currentPage < this.pageCount) {
                    this.currentPage++
                }
            },
            handleSearch() {
                this.$set(this.query, 'pageIndex', 1);
                this.getData();
            },

            // 触发重置按钮
            handleReset() {
                this.query.picName = "";
                this.query.picType = "";
                this.getData();
            },

            // 分页导航
            handlePageChange(val) {
                this.$set(this.query, 'pageIndex', val);
                this.getData();
            },

            onPreview(data) {
                this.showImg = true
                this.srcList[0] = data;
            },
            closeViewer() {
                this.showImg = false;
            },

            /*根据选择是图片还是PDF灵活上传控件*/
            selectPicType(val) {
                this.isImg = !this.isImg;
                this.imgurl = '';
                this.imgSrc = {};
                this.fileSize = 0;
                this.fileList = [];
            },

            // 新增操作
            handleAdd(index, row) {
                this.addForm = {};
                this.addForm.picType = "00";
                this.isImg = true;
                this.imgSrc = {};
                this.imgurl = '';
                this.fileSize = 0;
                this.fileList = [];
                this.addVisible = true;
            },
            /*新增用户*/
            saveAdd() {
                this.$refs['addForm'].validate((valid) => {
                    if (valid) {
                        let formData = new FormData();
                        /*图片*/
                        if (this.addForm.picType == '00') {
                            if (this.imgSrc.imgurl !== undefined) {
                                let imgTp = this.imgSrc.imgurl.substring(this.imgSrc.imgurl.indexOf("/") + 1, this.imgSrc.imgurl.indexOf(";"));
                                let imgData = this.imgSrc.imgurl.substring(this.imgSrc.imgurl.indexOf(",") + 1);
                                formData.append("picImgData", imgData);
                                formData.append("picImgTp", imgTp);
                                formData.append("picImgLen", this.imgSrc.imgLen);
                            } else {
                                this.$message.warning('请上传对应文件');
                                return;
                            }
                        } else {
                            /*PDF*/
                            if (this.fileSize !== 1) {
                                this.$message.warning('请上传对应文件');
                                return;
                            } else {
                                console.log("this.file", this.file);

                                formData.append("file", this.file);
                            }
                        }
                        formData.append("fkId", this.query.fkId);
                        formData.append("picType", this.addForm.picType);
                        formData.append("picName", this.addForm.picName);
                        this.addForm.picRmk = this.addForm.picRmk !== undefined ? this.addForm.picRmk : '';
                        formData.append("picRmk", this.addForm.picRmk);
                        console.log("传入后台的form表单", this.addForm);
                        //新增form表单提交到后台
                        doAddPicture(formData).then(res => {
                            if (res.success) {
                                this.addVisible = false;
                                this.addForm = {};
                                this.imgurl = '';
                                this.imgSrc = {};
                                this.fileSize = 0;
                                this.getData();
                                this.$message.success('保存成功');
                            } else {
                                this.$message.error('保存失败');
                            }
                        });
                    }
                });
            },
            closeAdd() {//关闭新增弹出框
                this.$confirm('确认关闭？', '提示', {
                    type: 'warning'
                })
                    .then(() => {
                        this.addVisible = false;
                        this.getData();
                    })
                    .catch(() => {
                        this.$message({
                            message: '已取消操作'
                        });
                    });
            },
            // 编辑操作
            async handleEdit(index, row) {
                await selectOnePic({picId: row.picId}).then(res => {
                    if (res.success) {
                        this.editForm = res.data;
                        this.editForm.picId = row.picId;
                        if (res.data.picType == '00') {
                            /*图片*/
                            this.isImg = true;
                            this.imgurl = 'data:image/' + res.data.picImgTp + ';base64,' + res.data.picImgData;
                            this.imgSrc={"imgLen":res.data.picImgLen};
                        } else {
                            /*PDF*/
                            this.isImg = false;
                            this.fileSize = 0;
                            this.fileList = [];
                            this.file = File;
                        }
                        this.editVisible = true;
                    } else {
                        this.$message.error('查询失败');
                    }
                });
            },
            closeEdit() {//关闭编辑弹出框
                this.$confirm('确认关闭？', '提示', {
                    type: 'warning'
                })
                    .then(() => {
                        this.editVisible = false;
                        this.editForm = {};
                        this.imgurl = '';
                        this.imgSrc = {};
                        this.fileSize = 0;
                        this.fileList = [];
                        this.file = File;
                        this.getData();
                    })
                    .catch(() => {
                        this.$message({
                            message: '已取消操作'
                        });
                    });
            },
            // 保存编辑
            saveEdit() {
                this.$refs['editForm'].validate((valid) => {
                        if (valid) {   //form表单提交到后台
                            console.log("---this.editForm", this.editForm);
                            let formData = new FormData();
                            formData.append("picId", this.editForm.picId);
                            formData.append("fkId", this.query.fkId);
                            formData.append("picType", this.editForm.picType);
                            formData.append("picName", this.editForm.picName);
                            formData.append("picRmk", this.editForm.picRmk);
                            if (this.editForm.picType == '00') {
                                console.log("图片是否存在",this.imgSrc.imgurl);
                                //图片
                                /*编辑时 说明图片已修改*/
                                if (this.imgSrc.imgurl !== undefined) {
                                    let imgTp = this.imgSrc.imgurl.substring(this.imgSrc.imgurl.indexOf("/") + 1, this.imgSrc.imgurl.indexOf(";"));
                                    let imgData = this.imgSrc.imgurl.substring(this.imgSrc.imgurl.indexOf(",") + 1);
                                    formData.append("picImgData", imgData);
                                    formData.append("picImgTp", imgTp);
                                    formData.append("picImgLen", this.imgSrc.imgLen);
                                    doUpdatePicture(formData).then(res => {
                                        if (res.success) {
                                            this.editVisible = false;
                                            this.editForm = {};
                                            this.getData();
                                            this.$message.success('编辑成功');
                                        } else {
                                            this.$message.error('编辑失败');
                                        }
                                    });
                                }else{
                                    //无更改
                                    let imgTp = this.imgurl.substring(this.imgurl.indexOf("/") + 1, this.imgurl.indexOf(";"));
                                    let imgData = this.imgurl.substring(this.imgurl.indexOf(",") + 1);
                                    formData.append("picImgData", imgData);
                                    formData.append("picImgTp", imgTp);
                                    formData.append("picImgLen", this.imgSrc.imgLen);
                                    console.log("formData",formData.toString());
                                    doUpdatePicture(formData).then(res => {
                                        if (res.success) {
                                            this.editVisible = false;
                                            this.editForm = {};
                                            this.getData();
                                            this.$message.success('编辑成功');
                                        } else {
                                            this.$message.error('编辑失败');
                                        }
                                    });
                                }
                            } else {
                                console.log("是否修改pdf",this.fileSize);
                                // PDF ==0.说明已存在文件，无修改
                                if (this.fileSize !== 1) {
                                    console.log("无修改-----",);
                                    /*formData.append("file", this.file);*/
                                    console.log("传入后台的form表单", this.file);
                                    doUpdatePicture(formData).then(res => {
                                        if (res.success) {
                                            this.editVisible = false;
                                            this.editForm = {};
                                            this.getData();
                                            this.$message.success('编辑成功');
                                        } else {
                                            this.$message.error('编辑失败');
                                        }
                                    });
                                } else {
                                    console.log("已经修改-----",);
                                    // fileSize ==1 已修改 二次缺
                                    this.$confirm('确定要覆盖原有文件吗？', '提示', {
                                        type: 'warning'
                                    })
                                        .then(() => {
                                            formData.append("file", this.file);
                                            console.log("传入后台的form表单", formData);
                                            doUpdatePicture(formData).then(res => {
                                                if (res.success) {
                                                    this.editVisible = false;
                                                    this.editForm = {};
                                                    this.getData();
                                                    this.$message.success('编辑成功');
                                                } else {
                                                    this.$message.error('编辑失败');
                                                }
                                            });
                                        })
                                        .catch(() => {
                                            this.$message({
                                                message: '已取消覆盖'
                                            });
                                        });
                                }
                            }
                            ;
                        }
                    }
                );
            },

            /*头像上传 新增时*/
            onchangeImgFun(e) {
                let file = e.target.files[0];
                // 获取图片的大小，做大小限制有用
                let imgSize = file.size;
                let _this = this;// this指向问题，所以在外面先定义
                // 比如上传头像限制5M大小，这里获取的大小单位是b
                // base64方法 2
                let reader = new FileReader();
                reader.readAsDataURL(file); // 读出 base64
                reader.onloadend = function () {
                    // 图片的 base64 格式, 可以直接当成 img 的 src 属性值
                    let dataURL = reader.result;
                    _this.imgSrc = {"imgurl": dataURL, "imgLen": imgSize};
                    _this.imgurl = dataURL;
                }
            },

            /*头像删除时*/
            handleDelete(index, row) {
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                })
                    .then(() => {
                        console.log("删除的picId", row.picId);
                        //后台进行删除操作
                        doDeletePicture({"picId": row.picId}).then(res => {
                            if (res.success) {
                                this.$message.success('删除成功');
                                this.getData();
                            } else {
                                this.$message.error('删除失败');
                                this.getData();
                            }
                        });
                    })
                    .catch(() => {
                        this.$message({
                            message: '已取消删除'
                        });
                    });
            },

            handlePost(item) {
                console.log(" 11handlePost   this.fileSize", this.fileSize);
                this.fileSize = this.fileSize + 1;
                console.log(" 22handlePost   this.fileSize", this.fileSize);
                if (this.fileSize == 1) {
                    this.file = item.file;
                } else {
                    this.$message.warning("当前只能上传一个文件");
                }
            },
            handleExceed() {
                this.$message.warning("当前只能上传一个文件");
            },
            handleRemove() {
                if (this.fileSize !== 0) {
                    this.fileSize = this.fileSize - 1;
                }
            },
            beforeUpload(file) {
                let extension = file.name.split(".");
                if (extension[extension.length - 1] !== "pdf") {
                    this.$message.error('请上传PDF类型的文件');
                    return false;
                }
                ;
            },
            // pdf加载时
            loadPdfHandler(e) {
                this.currentPage = 1 // 加载的时候先加载第一页
            },
            /*展示pdf*/
            showPdf(index, row) {
                console.log("row.picAdr---", row.picAdr);
                showPdf({"picAdr": row.picAdr}).then(res => {
                    this.src = this.getObjectURL(res);
                    console.log("0-----src", this.src);
                    this.currentPage = 1;// 首先加载第一页
                    this.pdfDlgVisible = true
                });
            },

            // 处理文件流
            getObjectURL(file) {
                let url = null
                if (window.createObjectURL !== undefined) { // basic
                    url = window.createObjectURL(file)
                } else if (window.webkitURL !== undefined) { // webkit or chrome
                    try {
                        url = window.webkitURL.createObjectURL(file)
                    } catch (error) {
                        console.log(error)
                    }
                } else if (window.URL !== undefined) { // mozilla(firefox)
                    try {
                        url = window.URL.createObjectURL(file)
                    } catch (error) {
                        console.log(error)
                    }
                }
                return url
            },

            /*关闭弹出框*/
            closeSee() {
                this.pdfDlgVisible = false;
            },
            //    下载
            handleLoad(index, row) {
                console.log("下载的fileNm",row.picName);
                window.location.href = "/api/srm/file/getPdf?picAdr=" + row.picAdr+'&fileName='+row.picName;
            }
        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }

    .table {
        width: 100%;
        font-size: 14px;
    }

    .red {
        color: #ff0000;
    }

    .mr10 {
        margin-right: 10px;
    }

    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
        /*border-radius 属性允许您为元素添加圆角边框！*/
        border-radius: 6px;
        background-clip: padding-box;
        border-top-left-radius: 6px;
        border-top-right-radius: 6px;
        border-bottom-right-radius: 6px;
        border-bottom-left-radius: 6px;
    }

    /*头像上传*/
    .user-header {
        position: relative;
        display: inline-block;
    }

    .user-header-com {
        width: 150px;
        height: 150px;
        /*  border-radius: 0%;*/
        display: inline-block;
        margin-left: 10px;
    }

    .header-upload-btn {
        position: absolute;
        left: 0;
        top: 0;
        opacity: 0;
        /* 通过定位把input放在img标签上面，通过不透明度隐藏 */
    }
</style>
